package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.alibaba.cola.exception.Exceptions;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeeTransferVendor;
import com.authine.cloudpivot.ext.service.OrganizationDataService;
import com.authine.cloudpivot.ext.utils.BoServiceUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.authine.mvp.app.launcher.dto.errorcode.ErrorCodeEnum;
import com.authine.mvp.app.launcher.rpc.SaveOrUpdateBO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;

import javax.ws.rs.POST;
import javax.ws.rs.Path;

import java.util.Collections;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * @ClassName TransferVendorService
 * @Description: 转采供应商
 * @Author fj
 * @Date 2021/8/23
 * @Version V1.0
 **/
@Path("TransferVendorService")
@Slf4j
public class TransferVendorService {
    public static final OrganizationDataService organizationDataService = new OrganizationDataService();

    /**
     * 保存转采供应商
     *
     * @param param 转采供应商信息
     * @return 响应结果
     */
    @Path("saveTransferVendor")
    @POST
    @Operation(summary = "保存转采供应商", tags = CUSTOM_SERVICE)
    public SingleResponse<BO> saveTransferVendor(@Parameter SaveOrUpdateBO param) {
        SingleResponse<BOList> transferVendorBOList = BoServiceUtils.findListBySimple(ModelConst.T_TRANSFER_VENDOR, "company_name", param.getData().get("company_name"));
        if (!transferVendorBOList.isSuccess()) {
            Exceptions.throwBizException(ErrorCodeEnum.BO_LIST_ERROR);
        }
        if (transferVendorBOList.getData().getTotal() > 0) {
            throw new BizException("供应商已存在，请勿重复添加！");
        }
        log.info("------------------------系统管理创建转采供应商数据：{}------------------------", JSONObject.toJSONString(param.getData()));
        SingleResponse<BO> createTransferVendorBO = BoServiceUtils.createBo(ModelConst.T_TRANSFER_VENDOR, Collections.singletonList(param.getData()));

        // 转采添加供应商同步金蝶供应商
        KingDeeTransferVendor kingDeeTransferVendor = KingDeeTransferVendor.builder()
                .id(createTransferVendorBO.getData().getBizObjectId())
                .companyName(String.valueOf(param.getData().get("company_name")))
                .build();
        organizationDataService.createTransferVendor(kingDeeTransferVendor);
        return createTransferVendorBO;
    }
}
